package cnpm.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import cnpm.dao.InsuranceDAO;
import cnpm.entity.Employee;
import cnpm.entity.Insurance;
import cnpm.util.HibernateUtil;

public class InsuranceDAOImpl implements InsuranceDAO {

	private SessionFactory sessionFactory;
	private Session session;
	
	public InsuranceDAOImpl() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}
	
	@Override
	public boolean saveOrUpdateInsurance(Insurance insu) {
		try{
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.saveOrUpdate(insu);
			session.beginTransaction().commit();
			return true;
		}catch(HibernateException e1){
			if(session.beginTransaction() == null){
				session.beginTransaction().rollback();
			}
			e1.printStackTrace();
		}finally{
			session.close();
		}
		return false;
	}

	@Override
	public boolean deleteInsurance(Insurance insu) {
		try{
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.delete(insu);
			session.beginTransaction().commit();
			return true;
		}catch(HibernateException e1){
			if(session.beginTransaction() == null){
				session.beginTransaction().rollback();
			}
			e1.printStackTrace();
		}finally{
			session.close();
		}
		return false;
	}

	//Khong chac
	@SuppressWarnings("unchecked")
	@Override
	public List<Insurance> getAllInsurance(Employee e) {
		List<Insurance> clist = null;
		try{
			session = sessionFactory.openSession();
			clist = session.createCriteria(Insurance.class)
					.add(Restrictions.eq("empInsurance", e)).list();
			return clist;
		}catch(HibernateException e1){
			e1.printStackTrace();
		}finally{
			session.close();
		}
		return clist;
	}

	@Override
	public Insurance getInsuranceByID(String insuranceID) {
		try{
			session = sessionFactory.openSession();
			return (Insurance) session.get(Insurance.class, insuranceID);
		}catch(HibernateException e){
			e.printStackTrace();
		}
		finally{
			session.close();
		}
		return null;
	}

}
